<?php

namespace App\Jobs;

use App\Http\Util\HomeTool;
use App\Models\Contract;
use App\Models\Paper;
use App\services\ImmService;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use OSS\OssClient;

class UploadTask implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $data;
    private $uid;
    public $tries = 2;
    public $timeout = 60;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($uid,$data)
    {
        $this->data = $data;
        $this->uid = $uid;
        //因为要导入大文件 需要很久时间
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $model = Contract::where('uid',$this->uid)->first();
        if(!$model){
            return '';
        }
        $date = date('Ymd',time());
        $config = [
            'accessId' => config('site.accessKeyId'),
            'accessKey' => config('site.accessSecret'),
            'endpoint' => config('site.point'),
            'bucket' => config('site.bucket')
        ];
        $ossClient = new OssClient($config['accessId'], $config['accessKey'], $config['endpoint']);
        try{
                $imgs = $this->data['result']['imageurls'];
                $model->png_count = count($imgs);
                $imglist = [];
                foreach( $imgs as $v){
                    $path = HomeTool::downloadfile($v , '/upload/temp/img');
                    $pathArr = explode('.',  $path);
                    $fileExt = end(  $pathArr  );
                    $img_path = 'img/'.$date.'/'.uniqid().'.'.$fileExt;

                    $result = $ossClient->uploadFile($config['bucket'],$img_path, public_path($path));
                    if ($result['info']) {
                       $imglist[] = $result['info']['url'];
                        Storage::disk('public_1')->delete($path);
                    }
                }

                $thumb = ImmService::makeWater($imgs[0],$model->title);
                $model->title_pic = $thumb;
                $model->png = json_encode($imglist);
                $model->save();
                dispatch(new ThumbTask($model->id,$thumb))->delay(now()->addSeconds(30))->onQueue('thumb');
        }catch (\Exception $e){
            Log::info('UploadTask-'.$model->id.'-导入失败，原因：'.$e->getMessage());
        }

    }
}

